package com.cet.programmercarl.algorithmperformancanalysis.链表;

/**
 * @program: algorithm
 * @description: 删除链表的倒数第N个节点
 * @author: 陈恩涛
 * @create: 2022-03-11 21:22
 **/
public class LC19 {

    public static void main(String[] args) {

    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        int length = 0;
        for (ListNode temp = head; temp != null; temp = temp.next) {
            length++;
        }
        ListNode dummy = new ListNode();
        dummy.next = head;
        ListNode pre = dummy;
        int target = length - n;
        while (target > 0) {
            pre = pre.next;
            target--;
        }
        pre.next = pre.next.next;
        return dummy.next;
    }
}

/**
 * 双指针的经典应用，如果要删除倒数第n个节点，
 * 让fast移动n步，然后让fast和slow同时移动，
 * 直到fast指向链表末尾。删掉slow所指向的节点就可以了。
 */
